package edu.xjtu.jih.demands;

import com.alibaba.fastjson.JSON;
import edu.xjtu.jih.common.Result;
import edu.xjtu.jih.common.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.util.UUID;
@MultipartConfig
@WebServlet({
        "/Demands_info",
        "/picture"
})
public class DemandsAPI extends HttpServlet {
    String image_url = "sss";

    @Override
    public void init() throws ServletException {
        File dir = new File("C:/images");//表示文件或目录的路径
        if(!dir.exists()){//目录不存在则创建
            dir.mkdirs();
        }
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");//设置请求编码，防止获取请求信息中文乱码
        String path = req.getServletPath();//获取请求路径
        if("/picture".equals(path)) {
            //System.out.println("000");
            try {
                Part part = req.getPart("picture");

                InputStream in = part.getInputStream();
                //System.out.println("001");
                String name = UUID.randomUUID().toString();//获得通过uuid算法得到的不重复的字符串
                String submittedFilename = part.getSubmittedFileName();//原始文件名
                String suffix = submittedFilename.substring(submittedFilename.lastIndexOf("."));
                String filename = name + suffix;
                OutputStream out = new FileOutputStream("C:/images" + "/" + filename);

                //System.out.println("002");
                image_url = filename;
                byte[] b = new byte[10240];//容量为10240字节的缓存区
                int len = -1;//从输入流读取并放入缓存区的数据量
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                Utils.outResult(resp, Result.success());
                out.flush();
                out.close();
                in.close();

            }catch (Exception e){
                e.printStackTrace();
            }finally {

            }
        }
        if("/Demands_info".equals(path)) {
            DemandsDto dto;
            try {
                Reader reader = req.getReader();
                CharArrayWriter out = new CharArrayWriter();//该输出流将数据输出到一个字符数组中
                boolean ok;
                try {
                    char[] charBuff = new char[1024];
                    int len = -1;//每次从输入流实际读取的字符数

                    while ((len = reader.read(charBuff)) != -1) {
                        out.write(charBuff, 0, len);
                    }
                    out.flush();

                    String json = out.toString();

                    dto = JSON.parseObject(json, DemandsDto.class);
                    int special_Item_Id = new DemandsService().selectMaxItemId()+1;
                    dto.setItem_image(image_url);
                    dto.setItem_id(special_Item_Id);
                    //System.out.println(dto.toString());
                    System.out.println(dto.getUser_id()+dto.getItem_id()+dto.getItem_name()+dto.getItem_price()+dto.getItem_desc()+dto.getItem_image()+dto.getItem_label());
                    ok = new DemandsService().checkInsert(dto);
                    //System.out.println("1");
                    image_url = "sss";


                } finally {
                    out.close();
                    reader.close();
                }
                if (ok) {
                    System.out.println("success!");
                    Utils.outResult(resp, Result.success("已成功提交！"));
                } else {
                    Utils.outResult(resp, Result.fail(Result.ERR_CODE_BUSINESS, "未成功提交！请重新检查输入内容。"));
                }

            } catch (Exception e) {
                Utils.outResult(resp, Result.fail(Result.ERR_CODE_SYS, "系统升级中......！"));
            }
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();//获取请求路径

        if("/picture".equals(path)){
            //从请求参数中通过参数名称filename获取文件名称
            String filename = request.getParameter("filename");
            //读取文件的输入流
            InputStream in = new FileInputStream("C:/images"+"/"+filename);
            //将文件信息输出到浏览器的输出流
            OutputStream out = response.getOutputStream();

            byte[] b = new byte[10240];//容量为10240字节的缓存区
            int len = -1;//从输入流读取并放入缓存区的数据量

            while((len=in.read(b))!=-1){
                out.write(b,0,len);
            }
            out.flush();
            out.close();
            in.close();

        }
    }
}
